package com.android.Translator.Model.utils;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Message;
import android.os.SystemClock;
import android.util.Log;

import com.example.entity.DataSearch;
import com.example.entity.DataTransalte;
import com.example.entity.Examples;
import com.example.entity.Means;
import com.example.entity.Words;
import com.example.provider.Provider;
import com.example.ultils.ConnectionDetector;
import com.android.Translator.Model.utils.JsonReader;
import com.android.Translator.Presenter.TranslatorPresenter;

//[Quan] -- Class Parser -- Class nay ke thua tu class AsyncTask dung de
// thuc hien
// qua trinh parse tren 1 thread khac
public class ParseJson extends AsyncTask<String, Void, DataSearch> {
		
		private Activity myActivity;
		private Provider db;
		private ConnectionDetector connectionN;
		private Boolean isInternetPresent = false;
		private boolean m_isMyWord;
		private String m_groupID;
		
		//[Quan] - Ham kiem tra string co chua cac ki tu latin
		private static final Pattern p = Pattern.compile("\\p{Alpha}+");
		static boolean isValid(String input) {
			  Matcher m = p.matcher(input);
			  return m.matches();
		}
		//end
		public ParseJson(Activity activity, Provider db, boolean isMyWord, String groupID) {
			// TODO Auto-generated constructor stub
			myActivity = activity;
			this.db = db;
			m_isMyWord = isMyWord;
			m_groupID = groupID;
		}
		
		@Override
		protected void onPreExecute() {
		// TODO Auto-generated method stub
			super.onPreExecute();
			if (m_isMyWord)
				TranslatorPresenter.showProcessCircle();
		}

		@Override
		protected DataSearch doInBackground(String... Phrase) {
			connectionN = new ConnectionDetector(
					myActivity.getApplicationContext());
			isInternetPresent = connectionN.isConnectingToInternet();
			if (isInternetPresent) {
				// [Quan] --gui request len voi cac params va lay ket qua
				// tra ve la 1 chuoi Json -- jsonStr
				List<NameValuePair> params = new ArrayList<NameValuePair>();
				params.add(new BasicNameValuePair("from", "eng"));
				params.add(new BasicNameValuePair("dest", "vie"));
				params.add(new BasicNameValuePair("format", "json"));
				params.add(new BasicNameValuePair("phrase", Phrase[0]));
				params.add(new BasicNameValuePair("pretty", "true"));
				String jsonStrMean = "";
				String jsonStrExam = "";
				
				jsonStrMean = JsonReader.getJsonFromURL(ModelConstants.REQUEST_URL, ModelConstants.GET, params);
				jsonStrExam = JsonReader.getJsonFromURL(ModelConstants.REQUEST_URL_EXMAM, ModelConstants.GET, params);
				DataSearch dataSearch = new DataSearch();
				if ((jsonStrMean != null && jsonStrMean != "")
						|| (jsonStrExam != null && jsonStrExam != "")) {
					// end
					// create a word
					Words word = new Words();
					word.setKeyword(Phrase[0]);
					word.setIdlang("0");
					if (m_isMyWord)
						word.setIsmine("true");
					else
						word.setIsmine("false");
					word.setPronoun("");
					word.setSound("");
					word.setDateinsert(Calendar.getInstance().getTime()
							.toString());
					word.setDateupdate(Calendar.getInstance().getTime()
							.toString());
					word.setDatedelete(Calendar.getInstance().getTime()
							.toString());
					word.setGroupId(m_groupID);
					db.createWords(word);

					Means mean = new Means();
					mean.setKeyword(Phrase[0]);
					mean.setIdlang("0");
					mean.setKindword("");
					mean.setContent(jsonStrMean);
					mean.setDest("1");
					mean.setDateinsert(Calendar.getInstance().getTime()
							.toString());
					mean.setDateupdate(Calendar.getInstance().getTime()
							.toString());
					mean.setDatedelete(Calendar.getInstance().getTime()
							.toString());
					db.createMeans(mean);

					Examples exam = new Examples();
					exam.setKeyword(Phrase[0]);
					exam.setIdlang("0");
					exam.setContent(jsonStrExam);
					exam.setDateinsert(Calendar.getInstance().getTime()
							.toString());
					exam.setDateupdate(Calendar.getInstance().getTime()
							.toString());
					exam.setDatedelete(Calendar.getInstance().getTime()
							.toString());
					db.createExample(exam);

					
					DataTransalte translate = new DataTransalte();
					translate = db.translate(Phrase[0]);
					if (translate != null) {
						if (translate.getMean() != null
								|| translate.getExam() != null) {
							try {

								ArrayList<String> lstMeans = new ArrayList<String>();
								ArrayList<String> lstExam = new ArrayList<String>();

								JSONObject jsonObjMean = new JSONObject(
										translate.getMean().getContent());
								JSONObject jsonObjExam = new JSONObject(
										translate.getExam().getContent());
								// Getting JSON Array node
								JSONArray meanJson = null;
								JSONArray examJson = null;

								meanJson = jsonObjMean.getJSONArray(ModelConstants.TAG_MEAN);
								examJson = jsonObjExam
										.getJSONArray(ModelConstants.TAG_EXAMPLE);
								// looping through All Contacts
								for (int i = 0; i < meanJson.length(); i++) {
									JSONObject c = meanJson.getJSONObject(i);
									if (c.has(ModelConstants.TAG_PHRASE)) {
										String meaning = c
												.getString(ModelConstants.TAG_PHRASE);
										JSONObject childObj = new JSONObject(
												meaning);
										String text = childObj
												.getString(ModelConstants.TAG_TEXT);
										//[Quan] kiem tra string chi co chu cai latin
										if (!isValid(text))
											lstMeans.add(text);
									}
								}

								for (int i = 0; i < examJson.length(); i++) {
									JSONObject c = examJson.getJSONObject(i);
									String author = c.getString(ModelConstants.TAG_AUTHORS);
									if (author.equals("31")) {
										String exampFirst = c
												.getString(ModelConstants.TAG_FIRST);
										String exampSecond = c
												.getString(ModelConstants.TAG_SECOND);
										//[Quan] kiem tra string chi co chu cai latin
										if (!isValid(exampFirst))
											lstExam.add(exampFirst);
										if (!isValid(exampSecond))
											lstExam.add(exampSecond);
									}

								}

								dataSearch.setLstExam(lstExam);
								dataSearch.setLstMean(lstMeans);

							} catch (JSONException e) {
								e.printStackTrace();
							}
						}
					}
				}

				// [Quan]--tra ve la danh sach cac tu duoc dich
				return dataSearch;
			}

			return null;
		}

		@Override
		protected void onPostExecute(final DataSearch result) {
			super.onPostExecute(result);
			// [Quan] -- day la ham ket thuc qua trinh dich
			// Result la list tra ve tu ham doInBackground ta se gui
			// message len handler de xuat ket qua nay ra ListView
			Thread th = new Thread(new Runnable() {
				@Override
				public void run() {
					SystemClock.sleep(300);
					Message msg = JsonReader.messageHandler.obtainMessage();
					msg.arg1 = m_isMyWord?1:0;
					msg.obj = result;
					Log.i("Tranlator", " msg.obj" + msg.obj.toString());
					JsonReader.messageHandler.sendMessage(msg);
				}
			});
			th.start();
			// end
		}

	}
